from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from zhouce.models import User,KeCheng,Gou
from zhouce.serializer import UserSER,KeChengSER,GouSER
# Create your views here.
class UserView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        level = request.data.get('level')
        userr = request.data.get('userr')
        user = UserSER(username=username, password=password, level=level, userr=userr)
        if userr == '1':
            # 判断数据验证
            if user.is_valid():
                user.save()
                return Response({'msg': '老师登陆成功', 'code': 200})
            else:
                return Response({'msg': '老师登陆失败', 'code': 500})

        else:
            # 判断数据验证
            if user.is_valid():
                user.save()
                return Response({'msg': '学生登陆成功', 'code': 200})
            else:
                return Response({'msg': '学生登陆失败', 'code': 500})






class KeCengView(APIView):
    def get(self,request):
        # 查看所有课程
        kecheng = KeCheng.objects.all()
        # 进行序列化查询多条数据
        kecheng_ser = KeChengSER(kecheng,many=True)
        # 返回结果
        return Response(kecheng_ser.data)


class GouView(APIView):
    def post(self,request):
        user_id = request.GET.get('user_id')
        kecheng_id = request.GET.get('kecheng_id')
        data = {
            'user_id':user_id,
            'kecheng_id':kecheng_id
        }
        gou = GouSER(data=data)
        if gou.is_valid():
            gou.save()
            return Response({'code':200})
        else:
            return Response({'code':500})